package com.demo.oauth2.client.myapp;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.common.OAuthProviderType;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.types.ResponseType;

import com.demo.oauth2.client.util.OAuth2ClientParams;

public class MyAppServlet extends HttpServlet {

	private static final long serialVersionUID = -6964848350214089906L;
	
	private final String TIPO_AUTH   = "tipo_auth";
	private final String TIPO_DEMO   = "demo";
	private final String TIPO_GOOGLE = "google";
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		String paramTipo = req.getParameter(TIPO_AUTH);
		OAuthClientRequest oauthRequest = null;
		
		try {
			
			if (paramTipo.equals(TIPO_DEMO)) {
				oauthRequest = OAuthClientRequest
						.authorizationLocation("http://localhost:8080/oauth2-server/webservice/oauth2")
						.setClientId(OAuth2ClientParams.DEMO_CLIENT_ID)
						.setRedirectURI(OAuth2ClientParams.DEMO_REDIRECT_URI)
						.setResponseType(ResponseType.CODE.toString())
						.buildQueryMessage();
			}
			else if (paramTipo.equals(TIPO_GOOGLE)) {
				oauthRequest = OAuthClientRequest
						.authorizationProvider(OAuthProviderType.GOOGLE)
						.setClientId(OAuth2ClientParams.GOOGLE_CLIENT_ID)
						.setRedirectURI(OAuth2ClientParams.GOOGLE_REDIRECT_URI)
						.setResponseType(ResponseType.CODE.toString())
						.setScope(OAuth2ClientParams.GOOGLE_SCOPE_USERINFO_EMAIL)
						.buildQueryMessage();
			}
			
			resp.sendRedirect(oauthRequest.getLocationUri());
		} 
		catch (OAuthSystemException e) {
			throw new ServletException(e);
		}
	}

}
